from urllib import request, parse
from threading import Thread

from dbpool import Mysql
import traceback
import public
import queue
import random
import time
import logging

perform_log = logging.getLogger('perform')
mysql_per = Mysql()

class Info_addclick(Thread):
    def __init__(self, Info_start_cl):
        Thread.__init__(self)
        self.url = public.info_add_url
        self.Info_start_cl = Info_start_cl

    def run(self):
        while True:
            try:
                if self.Info_start_cl.queuelist.empty() == True:
                    time.sleep(0.01)
                    continue
                push_data = self.Info_start_cl.queuelist.get()
                postdata = parse.urlencode({
                    'id': push_data[0]
                }).encode('utf-8')
                for i in range(push_data[1]):
                    req = request.Request(self.url, postdata)
                    uopen = request.urlopen(req)
                    uopen.close()
                    time.sleep(push_data[2])
                _push_sql = "UPDATE e_info SET py_click_rate = py_click_rate + %d where id=%d" % (push_data[1], push_data[0])
                mysql_per.updateOne(_push_sql)
                _log_str='%d 编号数据 已发起 %d 次请求，并写入数据库'% (push_data[0], push_data[1])
                print(_log_str)
            except BaseException as b:
                perform_log.error(b)

class Info_start(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.thread_counts = public.thread_count
        self.queuelist = queue.Queue()
        self.workerList = list()

    def worker_start(self):
        for i in range(self.thread_counts):
            _Info_addclick = Info_addclick(self)
            if _Info_addclick != None:
                _Info_addclick.start()
            self.workerList.append(_Info_addclick)

    def run(self):
        while True:
            _log_str = "当前队列堆积数量：" + str(self.queuelist.qsize())
            print(_log_str)
            time.sleep(60)
            # pe_logging.info(_log_str)

    def push_rule(self, id_list, wait_time):
        info_type_id = public.type_id
        info_channel_list = public.channel_list
        info_refresh_rate = public.refresh_rate
        for i in id_list:
            if i[2] == info_type_id:
                _push_num = random.randint(info_refresh_rate[0][0], info_refresh_rate[0][1])
            elif i[1] in info_channel_list:
                _push_num = random.randint(info_refresh_rate[1][0], info_refresh_rate[1][1])
            else:
                _push_num = random.randint(info_refresh_rate[2][0], info_refresh_rate[2][1])

            _frequency = round(wait_time / 12 / _push_num, 2)
            print(i[0], _push_num, _frequency)
            _frequency_list = [i[0], _push_num, _frequency]
            # print(_frequency_list)
            self.queuelist.put(_frequency_list)

